<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <style>
        #chat-body {
            width: 500px;
            height: 400px;
            resize: none;
            margin-bottom: 50px;
            background-color: darkgray;
            overflow-x: hidden;
            overflow-y: scroll;
        }
    </style>
</head>
<body>
<div style="width: 600px; height: 1000px; margin: 50px auto">

    <div style="width: 100%; margin-bottom: 50px">
        <label>输入昵称</label><input type="text" id="loginUserName"/>
        <input type="button" id="rest-user-bt" value="登陆/重置"/>
    </div>

    <div id="chat-body"></div>
    <br/>
    <label>输入消息</label><input type="text" name="msg" id="msg"/>
    <input type="button" id="send-bt" value="发送"/>
</div>
</body>
<script type="text/javascript">
    var userChatName = "";

    $(function () {
        // 获取登陆信息
        getUser();

        // 获取消息
        getMsgList();

        // 登陆
        $("#rest-user-bt").click(function () {
            var loginName = $("#loginUserName").val();
            $.ajax({
                url: "/chat/user/login",
                async: false,
                type: "post",
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                data: {
                    "nickName": loginName
                },
                success: function (msg) {
                    var token = msg.token;
                    setCookie("token", token);
                    getUser();
                }
            });
        });

        // 发送消息
        $(document).keyup(function (event) {
            if (event.keyCode === 13) {
                sendMsg();
            }
        });

        $("#send-bt").click(function () {
            sendMsg();
        });
    });

    var ws = new WebSocket("wss://chenxin1215.com/wss/chat/websocket");
    ws.onopen = function (evt) {
        console.log("Connection open ...");
    };
    ws.onmessage = function (evt) {
        var message = evt.data;
        console.log("Received Message: " + message);
        if (message === "getAllList") {
            getMsgList();
        } else if (message === "close") {
            ws.close();
        }
    };
    ws.onclose = function (evt) {
        console.log("Connection closed.");
    };

    function getUser() {
        var token = getCookie("token");
        $.ajax({
            url: "/chat/user/getUserInfo",
            async: false,
            type: "post",
            data: {
                "token": token
            },
            success: function (msg) {
                if (msg != null) {
                    userChatName = msg.nickName;
                }
            }
        });
    }

    function getMsgList() {
        var token = getCookie("token");
        $.ajax({
            url: "/chat/msg/getAllList",
            async: false,
            type: "post",
            data: {
                "token": token
            },
            success: function (msg) {
                var content = "";
                $("#loginUserName").html(userChatName);
                $.each(msg, function (index, value) {
                    var sendUserName = value.sendUserName;
                    if (userChatName === sendUserName) {
                        content += "<p style='text-align: right'>";
                    } else {
                        content += "<p style='text-align: left'>";
                    }
                    content += value.sendTime + "---" + sendUserName + " ：" + value.msg;
                    content += "</p><br>";
                });
                $("#chat-body").html(content);
            }
        });
    };

    function sendMsg() {
        var token = getCookie("token");
        var msg = $("#msg").val();
        $.ajax({
            url: "/chat/msg/sendMsg",
            async: false,
            type: "post",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "json",
            data: {
                "token": token,
                "msg": msg
            },
            success: function (result) {
                if (result != null && result === true) {
                    $("#msg").val("");
                } else {
                    alert("请先登陆");
                }
            }
        });
    }

    function setCookie(name, value, days) {
        var d = new Date();
        d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toGMTString();
        document.cookie = name + "=" + value + "; " + expires;
    }

    function getCookie(name) {
        name = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i].trim();
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
</script>
</html>